package cn.gson.crm.controller.emplo;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.gson.crm.controller.BaseServlet;
import cn.gson.crm.filter.LoginFilter;
import cn.gson.crm.model.dao.EmploDao;
import cn.gson.crm.model.entity.Employee;

/**
 * 员工登录
 */
@WebServlet("/login")
public class LoginServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
    private EmploDao emploDap = new EmploDao();


	/**
	 * 登录的设置
	 * @throws IOException 
	 * @throws ServletException 
	 */
    
    @Override
    protected void get(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	request.getRequestDispatcher("index.jsp").forward(request, response);
    }
	@Override
    protected void post(HttpServletRequest request, HttpServletResponse response) throws Exception, ServletException {
    	//获得参数
		String userName = request.getParameter("userName");
		String password = request.getParameter("passWord");
		
		//验证
		if(userName == null || userName.isEmpty()){
			erroForward("login", "账号不能为空！");
			return;
			//不能输入空格
		}else if(userName.trim() == null && userName.trim().isEmpty()){
			erroForward("login", "账号不能为空！");
			return;
		}
		if(password == null || password.isEmpty()){
			erroForward("login", "密码不能为空！");
			return;
			//不能输入空格
		}else if(password.trim() == null && password.trim().isEmpty()){
			erroForward("login", "密码不能为空！");
			return;
		}
		
		//通过用户名查找用户
		Employee e = emploDap.emploGetByUserName("正常",userName);
		//判断是否找到这个用户
		if(e != null && e.getPassword().equals(password)){
			request.getSession().setAttribute(LoginFilter.USER_SESSION_KEY, e);
			// 判断用户类型，来进行页面的跳转
			if(e.getEmploType() == 1){
				response.sendRedirect("after/login");
			}
		}else{
			request.setAttribute("erro", "账号或密码错误！");
			request.getRequestDispatcher("index.jsp").forward(request, response);
			return;
		}
    }
}
